package com.luci.security;

import com.luci.security.result.JwtUser;
import com.luci.security.support.ILogin;
import com.luci.security.support.ILoginBo;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

/**
 * 自定义认证提供者
 *
 * @author yuyanan
 * @version 1.0
 * @date 18-10-19
 */
public class DefaultProvider implements AuthenticationProvider {

    private ILogin iLogin;

    public DefaultProvider(ILogin iLogin) {
        this.iLogin = iLogin;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        ILoginBo loginParam = (ILoginBo) authentication.getDetails();
        JwtUser jwtUser = iLogin.login(loginParam);

        List<SimpleGrantedAuthority> roles = jwtUser.getRoles().stream().map(role -> new SimpleGrantedAuthority(role))
                                                    .collect(Collectors.toList());
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(null, null, roles);
        token.setDetails(jwtUser);
        return token;
    }

    /**
     * 只支持用户名密码token
     */
    @Override
    public boolean supports(Class<?> authentication) {
        return true;
    }
}
